<template>
  <div class="login-container">
    <!-- 头部标签 -->
    <div>
      <van-nav-bar
        title="登录"
        class="title"
      >
        <template #left>
          <img
            src="@/assets/images/logo.png"
            class="logo"
          >
        </template>
      </van-nav-bar>
    </div>
    <!-- 登录窗口 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="username"
        label="用户名"
        placeholder="请输入手机号"
        required
        :rules="[{  pattern, message: '请输入正确的手机号',trigger :'onChange' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="请输入密码"
        required
        :rules="[{  message: '请输入正确的密码', trigger: 'onChange', pattern: /^\d{6}$/ }]"
      />
      <div style="margin: 16px;">
        <van-button
          round
          block
          :loading='isloading'
          type="info"
          loading-text="加载中..."
          native-type="submit"
        >提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
// import { postLogin } from "@/api/login.js";
import { mapActions, mapState } from 'vuex'
// 导入局部组件必须在scrip里面导入,在App里面导入
export default {
  // 组件名称
  name: '',
  // 组件参数接收来自父组件的数据
  props: {},
  // 接收局部注册的组件
  components: {},
  // 组件数据
  data () {
    return {
      isloading: false,
      show: false,
      username: '15210412183',
      password: '246810',
      // 手机号正则验证
      pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/

    }
  },

  methods: {
    // 调用vuex异步请求
    ...mapActions(['asyncAction']),
    async onSubmit (values) {
      try {
        this.isloading = true
        // 调用vuex异步请求从vuex发送axios
        await this.asyncAction({
          mobile: values.username,
          code: values.password
        })
        this.$toast.success('登录成功')
        this.$router.push({
          // 登录成功之后 ,如果有from就去from的页面 没有就去首页
          path: this.$route.query.from || '/layout/home'
        })
      } catch (error) {
        this.$toast.fail('登陆失败')
      } finally {
        // 无论成功失败都会执行
        this.isloading = false
      }
    }

  }
}
</script>
<style lang="less" scoped>
.logo {
  width: 100px;
  height: 30px;
}
</style>
